package com.zdp.filesync.rsync.config;

import com.alibaba.nacos.shaded.com.google.common.collect.Sets;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Objects;
import java.util.Set;

@Data
@ConfigurationProperties("rsync")
@Slf4j
@Component
public class RsyncServerConfig {

    private String uid;
    private String gid;
    // yes or no ; default:yes ,common : no
    private String useChroot = "yes";
    // yes or no
    private String readOnly = "no";
    // 不知道干啥用
    private String list = "no";

    private Integer maxConnections = 4;

    private String pidfile;
    private String lockFile;
    private String logFile;
    private String motdFile;

    private String exclude;
    // yes or no
    private String transferLogging;
    private Integer timeout;
    // yse or no
    private String ignoreNonreadable;
    private String dontCompress;
    //  空格隔开
    private String hostsAllow;

    private String hostsDeny;

    private String configPath;

    private String pwdPath;

    private String userName = "root";

    private String password = "123456";

    private String ip;

    private String port = "873";

    // rsync bin 的目录
    private String rsyncBinPath;

    private Set<String> configItems = Sets.newHashSet(
            "uid","gid","port","use chroot","read only",
            "list","max connections","pidfile","lock file","log file",
            "motd file","exclude","transfer logging","timeout","ignore nonreadable",
            "dont compress","hosts allow","hosts deny"
    );


    public String buildIsExistRsyncServerBash(){
        return "ps -ef|grep rsync";
    }

    /**
     * 构建删除 密码文件的命令
     * @return
     */
    public String buildDelPwdBash(){
        return "rm -rf " + pwdPath;
    }

    /**
     * 构建密码文件
     * @return
     */
    public String buildAddPwdBash(){
        StringBuilder str = new StringBuilder();
        str.append("echo '").append(userName)
                .append(":").append(password)
                .append("' >> ")
                .append(pwdPath);
        return str.toString();
    }

    /**
     * 修改密码文件权限
     * @return
     */
    public String buildChmodPwdFileBash(){
        return "chmod 600 " + pwdPath;
    }

    /**
     * 构建删除配置文件命令
     * @return
     */
    public String buildDelConfigBash(){
        return "rm -rf " + configPath;
    }

    /**
     * 构建删除Pid文件命令
     * @return
     */
    public String buildDelPidFileBash(){
        return "rm -rf " + pidfile;
    }

    /**
     * 构建初始化 公共配置文件的命令
     * @return
     */
    public String buildInitConfigBash(){
        StringBuilder cmd = new StringBuilder();
        String config = buildRsyncConfig();
        if(StringUtils.isBlank(config)){
            throw new RuntimeException("构建rsync公共配置文件失败,获取到的配置内容为空，请检查配置文件中的配置项");
        }
        cmd.append("echo -e '").append(config).append("' >>").append(configPath);
        return cmd.toString();
    }

    /**
     * 构建rsync的公共配置文件
     * @return
     */
    public String buildRsyncConfig(){
        StringBuilder str = new StringBuilder();
        Field[] fields = this.getClass().getDeclaredFields();
        if(Objects.isNull(fields) || fields.length == 0){
            log.info("找不到RsyncServerConfig的成员变量");
            throw new RuntimeException("找不到RsyncServerConfig的成员变量");
        }
        for (Field field : fields) {
            String configItem = buildConfigItem(field);
            if(StringUtils.isNoneBlank(configItem)){
                str.append(configItem).append("\n");
            }
        }
        return str.toString();
    }

    private String buildConfigItem(Field field){
        if(Objects.isNull(field)){
            return "";
        }
        StringBuilder configItem = new StringBuilder();
        String fieldName = field.getName();
        for(Character c : fieldName.toCharArray()){
            if(Character.isUpperCase(c)){
                configItem.append(" ").append(Character.toLowerCase(c));
            }else{
                configItem.append(c);
            }
        }

        if(configItems.contains(configItem.toString())){
            try {
                Object value = field.get(this);
                if(Objects.isNull(value)){
                    return "";
                }else{
                    return configItem + " = " + value ;
                }
            } catch (IllegalAccessException e) {
                log.error("字段:{} 获取值失败",fieldName,e);
                throw new RuntimeException(e);
            }
        }else{
            return "";
        }

    }

    /**
     * 构建启动 rsync的命令
     * @return
     */
    public String buildStartBash(){
        StringBuilder str = new StringBuilder();
        str.append(rsyncBinPath)
                .append(" --daemon ")
                .append(" --config=")
                .append(configPath);
        return str.toString();
    }

    /**
     * 构建关闭 rsync服务的命令
     * @return
     */
    public String buildStopBash(){
        StringBuilder str = new StringBuilder();
        str.append(" ps -ef|grep rsync|grep -v grep|awk '{print $2}'|xargs kill -9");
        return str.toString();
    }

}
